import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import org.apache.commons.codec.binary.Base64;
import org.apache.http.*;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpResponseException;
import org.apache.http.client.ResponseHandler;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;

import java.io.IOException;
import java.io.InputStreamReader;
import java.io.Reader;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by weijianxing on 11/21/14.
 */
public class ApiPostDemo {
    private static final String apiUser = "请替换成自己的用户名";
    private static final String masterSecret = "请替换成自己的密码";
    public static void main(String args[]) {

        //httpclient 线程安全
        CloseableHttpClient httpclient = HttpClients.createDefault();

        //httppost 非线程安全
        HttpPost httppost = new HttpPost("http://www.jk189.net/api/bloodPressure/create.do");
        httppost.setHeader(HttpHeaders.USER_AGENT, "Apache-HttpClient-4.3.6");
        httppost.setHeader(HttpHeaders.CONTENT_TYPE, "application/x-www-form-urlencoded; charset=UTF-8");
        httppost.setHeader("Authorization", getAuthorization(apiUser, masterSecret));
        List<NameValuePair> params = new ArrayList<NameValuePair>();

        //提交参数及值
        params.add(new BasicNameValuePair("high", "120"));
        params.add(new BasicNameValuePair("low", "80"));
        params.add(new BasicNameValuePair("deviceId", "设备id"));
        httppost.setEntity(new UrlEncodedFormEntity(params, Consts.UTF_8));

        ResponseHandler<ApiResponse> responseHandler =
                new ResponseHandler<ApiResponse>() {
                    @Override
                    public ApiResponse handleResponse(HttpResponse response) throws IOException {
                        StatusLine statusLine = response.getStatusLine();

                        HttpEntity entity = response.getEntity();

                        //异常
                        if (statusLine.getStatusCode() >= 300) {
                            throw new HttpResponseException(
                                    statusLine.getStatusCode(),
                                    statusLine.getReasonPhrase());
                        }
                        if (entity == null) {
                            throw new ClientProtocolException("Response contains no content");
                        }
                        //将返回的json字符串序列化成json对象
                        Gson gson = new GsonBuilder().create();
                        ContentType contentType = ContentType.getOrDefault(entity);
                        Charset charset = contentType.getCharset();
                        Reader reader = new InputStreamReader(entity.getContent(), charset);
                        return gson.fromJson(reader, ApiResponse.class);
                    }
                };

        try {
            ApiResponse apiResponse = httpclient.execute(httppost, responseHandler);

            if (apiResponse.getStatus() == ApiResponse.ok) {
                //提交数据成功
            } else {
                throw new Exception(apiResponse.getMessage());
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private static String getAuthorization(String apiKey, String masterSecret) {
        String source = apiKey + ":" + masterSecret;
        return new String(Base64.encodeBase64(source.getBytes()));
    }
}
